package com.bk.servlet;

import com.alibaba.fastjson.JSON;
import com.bk.pojo.Book;
import com.bk.service.BookService;
import com.bk.service.impl.BookServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @Author 27435
 * @Date 2024/11/2015:16
 * @Version 1.0
 */

@WebServlet(urlPatterns = {"/books"})
public class BookServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求编码
        req.setCharacterEncoding("UTF-8");
        // 设置响应编码
        resp.setCharacterEncoding("UTF-8");
        // 设置响应类型
        resp.setContentType("application/json;charset=UTF-8");
        // 获取当前页码
        String pageNum = req.getParameter("pageNum");
        // 响应流
        PrintWriter out = resp.getWriter();
        // 设置分页参数
        PageHelper.startPage(Integer.valueOf(pageNum),3);
        // 调用业务层查询所有图书的方法
        BookService bookService = new BookServiceImpl();
        // 获取图书列表
        List<Book> books = bookService.getBooks();
        // 获取分页信息
        PageInfo<Book> pageInfo = new PageInfo<>(books);
        // 将数据转换为JSON格式
        String jsonString = JSON.toJSONString(pageInfo);
        // 输出JSON字符串到客户端
        out.print(jsonString);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

}
